<template>
  <div class="schedule-container">
    <h1 class="page-title">课表查看</h1>
    
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="学年学期">
          <el-select v-model="filterForm.semester" placeholder="请选择学期" @change="handleSemesterChange">
            <el-option
              v-for="item in semesterOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="周次">
          <el-select v-model="filterForm.week" placeholder="请选择周次" @change="handleWeekChange">
            <el-option
              v-for="item in weekOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="schedule-header">
      <div class="schedule-info">
        <h2>{{ currentSemester }}</h2>
        <h3>第{{ currentWeek }}周</h3>
        <div class="date-range">{{ weekDateRange }}</div>
      </div>
      <div class="schedule-actions">
        <el-button-group>
          <el-button :disabled="filterForm.week <= 1" @click="prevWeek">
            <el-icon><ArrowLeft /></el-icon> 上一周
          </el-button>
          <el-button type="primary" @click="getCurrentWeek">本周</el-button>
          <el-button :disabled="filterForm.week >= 20" @click="nextWeek">
            下一周 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </el-button-group>
        <el-button type="success" @click="printSchedule">
          <el-icon><Printer /></el-icon> 打印课表
        </el-button>
      </div>
    </div>
    
    <div class="schedule-table-container">
      <el-table :data="timeSlots" border style="width: 100%" :span-method="objectSpanMethod">
        <el-table-column prop="time" label="时间" width="100" />
        <el-table-column prop="monday" label="星期一">
          <template #default="scope">
            <div v-if="scope.row.monday" class="course-cell" :class="getCourseTypeClass(scope.row.monday)">
              <div class="course-name">{{ scope.row.monday.name }}</div>
              <div class="course-info">{{ scope.row.monday.teacher }}</div>
              <div class="course-info">{{ scope.row.monday.location }}</div>
              <div class="course-info">{{ scope.row.monday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="tuesday" label="星期二">
          <template #default="scope">
            <div v-if="scope.row.tuesday" class="course-cell" :class="getCourseTypeClass(scope.row.tuesday)">
              <div class="course-name">{{ scope.row.tuesday.name }}</div>
              <div class="course-info">{{ scope.row.tuesday.teacher }}</div>
              <div class="course-info">{{ scope.row.tuesday.location }}</div>
              <div class="course-info">{{ scope.row.tuesday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="wednesday" label="星期三">
          <template #default="scope">
            <div v-if="scope.row.wednesday" class="course-cell" :class="getCourseTypeClass(scope.row.wednesday)">
              <div class="course-name">{{ scope.row.wednesday.name }}</div>
              <div class="course-info">{{ scope.row.wednesday.teacher }}</div>
              <div class="course-info">{{ scope.row.wednesday.location }}</div>
              <div class="course-info">{{ scope.row.wednesday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="thursday" label="星期四">
          <template #default="scope">
            <div v-if="scope.row.thursday" class="course-cell" :class="getCourseTypeClass(scope.row.thursday)">
              <div class="course-name">{{ scope.row.thursday.name }}</div>
              <div class="course-info">{{ scope.row.thursday.teacher }}</div>
              <div class="course-info">{{ scope.row.thursday.location }}</div>
              <div class="course-info">{{ scope.row.thursday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="friday" label="星期五">
          <template #default="scope">
            <div v-if="scope.row.friday" class="course-cell" :class="getCourseTypeClass(scope.row.friday)">
              <div class="course-name">{{ scope.row.friday.name }}</div>
              <div class="course-info">{{ scope.row.friday.teacher }}</div>
              <div class="course-info">{{ scope.row.friday.location }}</div>
              <div class="course-info">{{ scope.row.friday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="saturday" label="星期六">
          <template #default="scope">
            <div v-if="scope.row.saturday" class="course-cell" :class="getCourseTypeClass(scope.row.saturday)">
              <div class="course-name">{{ scope.row.saturday.name }}</div>
              <div class="course-info">{{ scope.row.saturday.teacher }}</div>
              <div class="course-info">{{ scope.row.saturday.location }}</div>
              <div class="course-info">{{ scope.row.saturday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sunday" label="星期日">
          <template #default="scope">
            <div v-if="scope.row.sunday" class="course-cell" :class="getCourseTypeClass(scope.row.sunday)">
              <div class="course-name">{{ scope.row.sunday.name }}</div>
              <div class="course-info">{{ scope.row.sunday.teacher }}</div>
              <div class="course-info">{{ scope.row.sunday.location }}</div>
              <div class="course-info">{{ scope.row.sunday.weekRange }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="course-legend">
      <div class="legend-title">图例：</div>
      <div class="legend-item">
        <div class="legend-color required"></div>
        <span>必修课</span>
      </div>
      <div class="legend-item">
        <div class="legend-color elective"></div>
        <span>选修课</span>
      </div>
      <div class="legend-item">
        <div class="legend-color general"></div>
        <span>通识课</span>
      </div>
      <div class="legend-item">
        <div class="legend-color lab"></div>
        <span>实验课</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight, Printer } from '@element-plus/icons-vue'
import { studentApi, commonApi } from '@/api'

// 筛选表单
const filterForm = ref({
  semester: '2023-2024-1',
  week: 1
})

// 学期选项
const semesterOptions = ref([])

// 周次选项
const weekOptions = Array.from({ length: 20 }, (_, i) => ({
  value: i + 1,
  label: `第${i + 1}周`
}))

// 当前学期和周次
const currentSemester = computed(() => {
  const semester = semesterOptions.value.find(item => item.value === filterForm.value.semester)
  return semester ? semester.label : ''
})

const currentWeek = computed(() => filterForm.value.week)

// 周日期范围
const weekDateRange = computed(() => {
  // 模拟计算周日期范围
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth()
  const day = now.getDate()
  
  // 假设学期开始日期是9月1日
  const semesterStart = new Date(2023, 8, 1) // 月份从0开始，8表示9月
  
  // 计算当前周的开始日期（周一）
  const weekStart = new Date(semesterStart)
  weekStart.setDate(semesterStart.getDate() + (filterForm.value.week - 1) * 7)
  
  // 计算当前周的结束日期（周日）
  const weekEnd = new Date(weekStart)
  weekEnd.setDate(weekStart.getDate() + 6)
  
  // 格式化日期
  const formatDate = (date) => {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }
  
  return `${formatDate(weekStart)} - ${formatDate(weekEnd)}`
})

// 课程时间段
const timeSlots = ref([])

// 初始化数据
onMounted(async () => {
  await fetchSemesters()
  fetchSchedule()
})

// 获取学期列表
const fetchSemesters = async () => {
  try {
    const res = await commonApi.getSemesters()
    if (res.code === 200 && res.data) {
      semesterOptions.value = res.data
      
      // 获取当前学期
      const currentRes = await commonApi.getCurrentSemester()
      if (currentRes.code === 200 && currentRes.data) {
        filterForm.value.semester = currentRes.data.value
      }
    }
  } catch (error) {
    console.error('获取学期列表失败:', error)
  }
}

// 获取课表数据
const fetchSchedule = async () => {
  try {
    // 初始化时间段
    timeSlots.value = [
      { time: '08:00-08:45\n第1节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '08:55-09:40\n第2节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '10:00-10:45\n第3节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '10:55-11:40\n第4节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '14:00-14:45\n第5节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '14:55-15:40\n第6节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '16:00-16:45\n第7节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '16:55-17:40\n第8节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '19:00-19:45\n第9节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null },
      { time: '19:55-20:40\n第10节', monday: null, tuesday: null, wednesday: null, thursday: null, friday: null, saturday: null, sunday: null }
    ]
    
    const res = await studentApi.getSchedule({
      semester: filterForm.value.semester,
      week: filterForm.value.week
    })
    
    if (res.code === 200 && res.data) {
      // 填充课表
      const courses = transformScheduleData(res.data)
      fillSchedule(courses)
    }
  } catch (error) {
    console.error('获取课表数据失败:', error)
    ElMessage.error('获取课表数据失败')
  }
}

// 转换课表数据格式
const transformScheduleData = (scheduleData) => {
  const courses = []
  
  // 处理API返回的课表数据
  scheduleData.forEach(item => {
    // 解析每一行的课程数据
    Object.keys(item).forEach(key => {
      if (key !== 'time' && item[key]) {
        const courseInfo = item[key].split('\n')
        if (courseInfo.length >= 3) {
          courses.push({
            name: courseInfo[0],
            location: courseInfo[1],
            teacher: courseInfo[2],
            time: `${getDayFromKey(key)} ${getTimeSlotFromTimeString(item.time)}`,
            weekRange: '1-16周', // 默认周次范围
            type: '必修' // 默认课程类型
          })
        }
      }
    })
  })
  
  return courses
}

// 根据key获取星期几
const getDayFromKey = (key) => {
  switch (key) {
    case 'monday': return '周一'
    case 'tuesday': return '周二'
    case 'wednesday': return '周三'
    case 'thursday': return '周四'
    case 'friday': return '周五'
    case 'saturday': return '周六'
    case 'sunday': return '周日'
    default: return ''
  }
}

// 从时间字符串获取节次
const getTimeSlotFromTimeString = (timeStr) => {
  // 示例: '第1-2节'
  if (timeStr.includes('-')) {
    return timeStr.replace('第', '').replace('节', '')
  }
  return '1-2'
}

// 填充课表
const fillSchedule = (courses) => {
  courses.forEach(course => {
    // 解析上课时间
    const { day, startSlot, endSlot } = parseTimeSlot(course.time)
    
    // 填充对应的时间段
    if (day && startSlot >= 1 && startSlot <= 10) {
      const dayKey = getDayKey(day)
      
      if (dayKey) {
        // 设置课程信息到第一个时间段
        timeSlots.value[startSlot - 1][dayKey] = {
          name: course.name,
          teacher: course.teacher,
          location: course.location,
          weekRange: course.weekRange,
          type: course.type,
          rowspan: endSlot - startSlot + 1 // 计算跨行数
        }
        
        // 将后续时间段设置为null（用于合并单元格）
        for (let i = startSlot; i < endSlot; i++) {
          timeSlots.value[i][dayKey] = null
        }
      }
    }
  })
}

// 解析时间段
const parseTimeSlot = (timeStr) => {
  // 示例格式：'周一 1-2节'
  const parts = timeStr.split(' ')
  if (parts.length < 2) return { day: null, startSlot: 0, endSlot: 0 }
  
  const day = parts[0]
  const slotRange = parts[1].replace('节', '').split('-')
  
  const startSlot = parseInt(slotRange[0])
  const endSlot = slotRange.length > 1 ? parseInt(slotRange[1]) : startSlot
  
  return { day, startSlot, endSlot }
}

// 获取星期几对应的属性名
const getDayKey = (day) => {
  switch (day) {
    case '周一': return 'monday'
    case '周二': return 'tuesday'
    case '周三': return 'wednesday'
    case '周四': return 'thursday'
    case '周五': return 'friday'
    case '周六': return 'saturday'
    case '周日': return 'sunday'
    default: return null
  }
}

// 获取课程类型对应的样式类名
const getCourseTypeClass = (course) => {
  if (!course || !course.type) return ''
  
  switch (course.type) {
    case '必修': return 'required'
    case '选修': return 'elective'
    case '通识': return 'general'
    case '实验': return 'lab'
    default: return ''
  }
}

// 表格合并单元格方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    // 时间列不合并
    return {
      rowspan: 1,
      colspan: 1
    }
  }
  
  // 获取列名
  const dayKeys = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
  const dayKey = dayKeys[columnIndex - 1]
  
  if (!dayKey) return
  
  const course = row[dayKey]
  
  if (course && course.rowspan) {
    return {
      rowspan: course.rowspan,
      colspan: 1
    }
  } else if (course === null) {
    // 被合并的单元格
    return {
      rowspan: 0,
      colspan: 0
    }
  }
  
  // 默认不合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

// 处理筛选
const handleFilter = () => {
  fetchSchedule()
}

// 重置筛选条件
const resetFilter = async () => {
  // 获取当前学期
  try {
    const res = await commonApi.getCurrentSemester()
    if (res.code === 200 && res.data) {
      filterForm.value.semester = res.data.value
    }
  } catch (error) {
    console.error('获取当前学期失败:', error)
  }
  
  filterForm.value.week = 1
  fetchSchedule()
}

// 处理学期变更
const handleSemesterChange = () => {
  fetchSchedule()
}

// 处理周次变更
const handleWeekChange = () => {
  fetchSchedule()
}

// 上一周
const prevWeek = () => {
  if (filterForm.value.week > 1) {
    filterForm.value.week--
    fetchSchedule()
  }
}

// 下一周
const nextWeek = () => {
  if (filterForm.value.week < 20) {
    filterForm.value.week++
    fetchSchedule()
  }
}

// 获取当前周
const getCurrentWeek = async () => {
  // 获取当前学期和周次
  try {
    const res = await commonApi.getCurrentSemester()
    if (res.code === 200 && res.data) {
      filterForm.value.semester = res.data.value
      // 假设当前是第几周
      filterForm.value.week = Math.floor(Math.random() * 16) + 1
      fetchSchedule()
    }
  } catch (error) {
    console.error('获取当前学期和周次失败:', error)
    ElMessage.error('获取当前学期和周次失败')
  }
}

// 打印课表
const printSchedule = () => {
  window.print()
}
</script>

<style lang="scss" scoped>
.schedule-container {
  padding: 20px;
  
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
  
  .filter-container {
    margin-bottom: 20px;
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    
    .filter-form {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      align-items: flex-start;
      
      :deep(.el-form-item) {
        margin-right: 0;
        margin-bottom: 10px;
        min-width: 200px;
        flex: 1;
      }
      
      :deep(.el-form-item:last-child) {
        flex: 0 0 auto;
      }
      
      :deep(.el-select) {
        width: 100%;
      }
      
      :deep(.el-input) {
        width: 100%;
      }
    }
  }
  
  .schedule-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .schedule-info {
      h2 {
        margin: 0 0 5px;
        font-size: 18px;
        color: #303133;
      }
      
      h3 {
        margin: 0 0 5px;
        font-size: 16px;
        color: #606266;
      }
      
      .date-range {
        font-size: 14px;
        color: #909399;
      }
    }
    
    .schedule-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .schedule-table-container {
    margin-bottom: 20px;
    
    :deep(.el-table) {
      .el-table__header th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: bold;
        text-align: center;
      }
      
      .el-table__row td {
        padding: 5px;
        vertical-align: top;
      }
    }
    
    .course-cell {
      padding: 8px;
      height: 100%;
      border-radius: 4px;
      display: flex;
      flex-direction: column;
      
      &.required {
        background-color: #ecf5ff;
        border-left: 3px solid #409EFF;
      }
      
      &.elective {
        background-color: #f0f9eb;
        border-left: 3px solid #67C23A;
      }
      
      &.general {
        background-color: #fdf6ec;
        border-left: 3px solid #E6A23C;
      }
      
      &.lab {
        background-color: #fef0f0;
        border-left: 3px solid #F56C6C;
      }
      
      .course-name {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .course-info {
        font-size: 12px;
        color: #606266;
        margin-bottom: 3px;
      }
    }
  }
  
  .course-legend {
    display: flex;
    align-items: center;
    margin-top: 20px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    .legend-title {
      margin-right: 15px;
      font-weight: bold;
    }
    
    .legend-item {
      display: flex;
      align-items: center;
      margin-right: 20px;
      
      .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 3px;
        margin-right: 5px;
        
        &.required {
          background-color: #ecf5ff;
          border-left: 3px solid #409EFF;
        }
        
        &.elective {
          background-color: #f0f9eb;
          border-left: 3px solid #67C23A;
        }
        
        &.general {
          background-color: #fdf6ec;
          border-left: 3px solid #E6A23C;
        }
        
        &.lab {
          background-color: #fef0f0;
          border-left: 3px solid #F56C6C;
        }
      }
    }
  }
}

// 打印样式
@media print {
  .filter-container,
  .schedule-actions,
  .course-legend {
    display: none !important;
  }
  
  .schedule-header {
    text-align: center;
    margin-bottom: 30px;
  }
}
</style> 